window.onload = function (){
    initUser();
    findByItem(1);
}

/**
 * 显示用户登录信息
 */
function initUser() {
    axios.get("/user/getLoginUser").then(resp =>{
        var info = resp.data;
        if (info== ""){
            $('userDiv').innerHTML = "你好，请先<a href='/login.html'>登录</a>"
        }
        else {
            $('userDiv').innerHTML = "欢迎光临"+info.username+"<a href='/custom/shop.html' style='display: inline-block;margin-right: 20px;margin-left: 10px'>查看购物车</a>"+
            "<a href='/custom/findOrder.html'>查看订单</a>";
        }
    })

}

/**
 * 动态条件分页查商品
 * @param pageNO 页码
 */
function findByItem(pageNO){
axios.get("/product/findByItem",{
    params:{
        pageNO,
        startDate:$('startTxt').value,
        appendData:$('endTxt').value,
        name:$('nameTxt').value
    }
}).then(resp=>{
    var info = resp.data;
    var str = ""
    info.records.forEach(n =>{
        str += `<div style="width: 300px;height: 300px;text-align: center">
            <img src="/productImg/${n.imgPath}" width="200" height="200"><br/>
            商品名:${n.name}<br/>
            单价:${n.price}<br/>
            已售数:${n.sealNum}<br/>
            <input type="button" value="查看" onclick="showProduct(${n.id})">
            <input type="button" value="购买" onclick="buy(${n.id})">

</div>`
    });
    $('productDiv').innerHTML = str;

    var cutStr = ""
    for (let i = 1; i <= info.pages ; i++) {
        cutStr += `<a style="margin-left: 10px;" href="javascript:findByItem(${i})">${i}</a>`
    }
    $('cutPageDiv').innerHTML = cutStr;
});
}

function buy(productId) {
    axios.get("/shop/buy",{
        params: {productId}
    }).then(resp =>{
        if (resp.data=="ok"){
            location.href = "/custom/shop.html"
        }else{
            location.href = "/login.html?errorInfo=noCustom"
        }
    })

}

function showProduct(productId) {
    axios.get("/product/showProduct",{
        params:{productId}
    }).then(resp =>{
        if (resp.data != ""){
            location.href  = "/findProduct.html?productId="+resp.data.id
        }
    })
}